package com.boot2.core.web;

import com.boot2.core.utils.CheckUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * @author zhangweilin
 * @date 2020/5/21 16:02
 * @Description:
 */
@CommonsLog
public abstract class AbstractClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    @Autowired(required = false)
    Map<String, RestTemplateInterceptor> restTemplateInterceptorMap;

    @PostConstruct
    public void init() {
        if (CheckUtil.isEmpty(restTemplateInterceptorMap)) {
            return;
        }
//        将url前缀当key
        restTemplateInterceptorMap = restTemplateInterceptorMap.entrySet().stream().collect(Collectors.toMap(k -> k.getValue().getBaseUrl(), v -> v.getValue()));
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
//        String scheme = request.getURI().getScheme();
//        String host = request.getURI().getHost();
//        String baseUrl = scheme + "://" + host + "/";
        String url = request.getURI().toString();
        Iterator<Entry<String, RestTemplateInterceptor>> iterator = restTemplateInterceptorMap.entrySet().iterator();
        while (iterator.hasNext()) {
            RestTemplateInterceptor restTemplateInterceptor = iterator.next().getValue();
            String baseUrl = restTemplateInterceptor.getBaseUrl();
            if (url.startsWith(baseUrl)) {
                ClientHttpResponse clientHttpResponse = restTemplateInterceptor.startIntercept(request, body, execution);
                return clientHttpResponse;
            }
        }
        log.info("当前url【" + request.getURI() + "】未配置拦截器，将采用系统默认拦截器");
        ClientHttpResponse clientHttpResponse1 = restTemplateInterceptorMap.get(DefaultRestTemplateInterceptor.defaultBaseUrl).startIntercept(request, body, execution);
        return clientHttpResponse1;
    }


}